package com.dap.utils;

import com.dap.commons.Constants;
import org.slf4j.MDC;
import org.springframework.util.StringUtils;

/**
 * @author wangmin
 * @discription
 * @created 2019-10-16 15:47
 */
public abstract class TraceIdUtils {
    public static String getTraceId() {
        return MDC.get(Constants.TRACE_ID);
    }

    public static void setTraceId(String traceId) {
        MDC.put(Constants.TRACE_ID, traceId);
    }

    public static String generateTraceId(boolean isForce) {
        if (isForce) {
            String traceId = LongStringIdUtil.generateId();
            MDC.put(Constants.TRACE_ID, traceId);
            return traceId;
        } else {
            String traceId = MDC.get(Constants.TRACE_ID);
            if (StringUtils.isEmpty(traceId)) {
                traceId = LongStringIdUtil.generateId();
                MDC.put(Constants.TRACE_ID, traceId);
            }
            return traceId;
        }
    }

    public static void removeTraceId() {
        MDC.remove(Constants.TRACE_ID);
    }
}
